package com.imooc.study.database

import java.sql.{Connection, DriverManager, SQLException, Statement}

object JdbcTest {

  def main(args: Array[String]): Unit = {

    var conn: Connection = null
    var pstm: Statement = null
    val url = "jdbc:mysql://centos704:3306/flume"
    val user = "root"
    val password = "123456"
    val sql = "select id,name,age,city,create_time from user"
    try {
      Class.forName("com.mysql.jdbc.Driver")
      conn = DriverManager.getConnection(url, user, password)
      pstm = conn.createStatement
      val hasResultSet = pstm.execute(sql)
      if (hasResultSet) {
        val rs = pstm.getResultSet
        while (rs.next) {
          val id = rs.getInt("id")
          val name = rs.getString("name")
          val age = rs.getInt("age")
          val city = rs.getString("city")
          val create_time_date = rs.getDate("create_time")
          val create_time_time = rs.getTime("create_time")
          println(s"$id,$name,$age,$city,$create_time_date $create_time_time")
        }
      }
    } catch {
      case e1: ClassNotFoundException => e1.printStackTrace()
      case e2: SQLException => e2.printStackTrace()
    } finally {
      if (pstm != null) {
        pstm.close()
      }
      if (conn != null) {
        conn.close()
      }
    }
  }
}
